package com.rongzhe.house.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.rongzhe.house.R;
import com.rongzhe.house.manager.HouseManager;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.SELECTION_MODE_SINGLE;

/**
 * Created by huang on 2017/11/27.
 */

public class FilterDateFragment extends FilterFragment {
    @BindView(R.id.calendarView)
    MaterialCalendarView calendarView;
    @BindView(R.id.btn_reset)
    Button btnReset;
    @BindView(R.id.btn_ok)
    Button btnOk;
    Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_date_choose_filter, container, false);
        unbinder = ButterKnife.bind(this, view);
        calendarView.setSelectionMode(SELECTION_MODE_SINGLE);
        Calendar current = Calendar.getInstance();
        Calendar maxCalendar = Calendar.getInstance();
        maxCalendar.add(Calendar.MONTH, 3);
        calendarView.state().edit().setMinimumDate(current.getTime())
                .setMaximumDate(maxCalendar.getTime()).commit();
        calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget,
                                       @NonNull CalendarDay date, boolean selected) {
                if(selected) {
                    btnOk.setEnabled(true);
                    btnReset.setEnabled(true);
                }
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.btn_ok)
    public void onOkClick() {
        CalendarDay choosed = calendarView.getSelectedDate();
        if (choosed == null) {
            return;
        }
        HouseManager.getInstance().setTime(String.valueOf(choosed.getCalendar().getTimeInMillis()));
        finishFragment();
    }

    @OnClick(R.id.btn_reset)
    public void onResetClick() {
        HouseManager.getInstance().setTime(null);
        calendarView.clearSelection();
        finishFragment();
    }
}
